<template>
  <div class='w-full h-full' ref='tablecontainer'>
    <div v-if='props.showctl' class='w-full h-8 flex justify-between items-center'>
      <n-space clas="h-full  px-1"  size="small">
        <div></div>
      </n-space>
      <n-space clas="h-full px-1" size="small">
        <n-dropdown trigger="click" :options="options">
         <n-button text size="small" type="info" bordered>
            <template #icon>
              <n-icon>
                <SettingOutlined />
              </n-icon>
            </template>
          </n-button>
        </n-dropdown>
        <n-dropdown trigger='hover' :options='sizeoptions' @select='handleSelect'>
        <n-button text size="small" type="info" bordered>
            <template #icon>
              <n-icon>
                <TextFontSize24Filled />
              </n-icon>
            </template>
          </n-button>
        </n-dropdown>
      </n-space>
    </div>
    <n-data-table
      :columns='newcolumn' :data='props.tabledata' :bordered='false' :size='tablesize'
      :row-key="(rowData)=>rowData.id" :scroll-x='tableWidth'
      :max-height='tableHeight' :row-class-name='rowClassName' :loading='props.loading'>
      <template #empty>
        <n-result description='空的'>
          <template #icon>
            <n-image width='70' height='70' :src='kong.url' preview-disabled></n-image>
          </template>
        </n-result>
      </template>
    </n-data-table>
  </div>
</template>

<script setup name='flextable' lang='ts'>
import Draggable from 'vuedraggable'
import { h, ref, defineProps, computed, watch, onMounted, onUnmounted, nextTick } from 'vue'
import {
  SettingOutlined,
  CheckOutlined,
} from '@vicons/antd'
import { TextFontSize24Filled } from '@vicons/fluent'
import { DragIndicatorOutlined } from "@vicons/material"
import { NSwitch, NIcon, NDataTable, NButton, NSpace } from 'naive-ui'
import kongimg from '@/assets/img/kong.webp'
// 没有数据时显示的图片
const kong = ref({
  url: kongimg,
})
const tablecontainer = ref(null)
const props = defineProps({
  column: {
    type: Array,
    default(data: any) {
      if (Array.isArray(data)) {
        return data
      } else {
        return [data]
      }
    },
  },
  tabledata: {
    type: Array,
    default(data: any) {
      if (Array.isArray(data)) {
        return data
      } else {
        return [data]
      }
    },
  },
  // 是否显示顶部的控制
  showctl: {
    type: Boolean,
    default: true,
  },
  // loading状态控制
  loading: {
    type: Boolean,
    default: false,
  },
})
// 字段列表
const thiscolumns = ref([])
const getcollumns = () => {
  thiscolumns.value = props.column.map((item: any, index: number) => {
    return { index, ...item, }
  })
}
// 监听外部的字段列表的变化，如果变了就重置一次
watch(() => props.column, () => {
  getcollumns()
})

const tablesize = ref<"small" | "medium" | "large">('small')
// 选中的图标，就是个对号
const tubiao = h(NIcon, { size: 20, color: 'blue' }, {
  default() {
    return [h(CheckOutlined, null, null)]
  },
})
// 测试控制行高
const rowClassName = ref('')
// 表格的高度
const tableHeight = ref(150)
// 表格的宽度
const tableWidth = ref("1000")
const sizeoptions = ref([
  {
    label: '紧凑', key: 'small', icon: () => {
      return tablesize.value === 'small' ? tubiao : null
    },
  },
  {
    label: '默认', key: 'medium', icon: () => {
      return tablesize.value === 'medium' ? tubiao : null
    },
  },
  {
    label: '宽松', key: 'large', icon: () => {
      return tablesize.value === 'large' ? tubiao : null
    },
  },
])
// 过滤后的字段属性
const newcolumn = computed(() => {
  return thiscolumns.value.filter((item: any) => item.show)
})
// 选择某个字段
const handleSelect = (key) => {
  tablesize.value = key
}
// 顶部状态
const allshow = ref(true)
// 顶部开关
const changeshow = (jieguo) => {
  console.log(jieguo,"显示是什么状态");

  allshow.value = jieguo
  thiscolumns.value.forEach((item: any) => {
    item.show = jieguo
  })
}
// 点击重置
const chongzhi = () => {
  allshow.value = true
  getcollumns()
}

// 计算表格的高度
const getheight = () => {
  if (tablecontainer.value) {
    // 外壳的高度，减去自己的顶部div和外层底部的分页高度
    tableHeight.value = tablecontainer.value.offsetHeight - 40 - 46
  } else {
    tableHeight.value = 150
  }
  console.log(tableHeight.value, '现在的高度')
  // 计算表格的宽度
  if (tablecontainer.value) {
    console.log(tablecontainer.value,"waiceng")
    const trdom = tablecontainer.value.getElementsByClassName("n-data-table-tr")
    console.log(trdom,"这个元素是不是存在啊")
    tableWidth.value = trdom && trdom.length > 0 ? trdom[0].offsetWidth.toString() : "100%"
  }
}
// 套壳进行延时计算
const calculation = () => {
  nextTick(()=>{
    getheight()
  })
}

// 阻止火狐浏览器的拖拽导致打开百度搜索的bug
const end1 = () => {
  document.body.ondrop = (event: any) => {
    event.preventDefault();
    event.stopPropagation();
  }
}

// 下拉框内容，纯html渲染
const options = ref([
  {
    key: 'header',
    type: 'render',
    render: () => {
      return h(NSpace,{justify:"space-between",class:{"p-1":true}},{default(){
        return [
          h(NSwitch, { value: allshow.value, 'onUpdate:value':changeshow }, { default() { } }),
          h(NButton,{text:true,class:{"dianji text-blue-400":true},onClick:chongzhi},{default(){return "重置"}}),
        ]
      }})
    }
  },
  {
    key: 'header',
    type: 'render',
    render: () => {
      return h(Draggable, {
        list: thiscolumns.value, "item-key": 'name', animation: 100,
        sort: true, class: { "h-full w-full flex flex-col max-h-800px overflow-hidden p-1": true },
        onEnd:end1,
      }, {
        item({ element }) {
          return [
            h(NSpace, {class:{"py-2px":true}}, {
              default() {
                return [
                  h(NIcon, {class:{"cursor-move":true}}, {
                    default() {
                      return [
                        h(DragIndicatorOutlined, null, { default() { } })
                      ]
                    }
                  }),
                  h(NSwitch, { value: element.show,size:"small", 'onUpdate:value': (val) => { element.show = val } }, { default() { } }),
                  h("span", null, { default() { return element.title } })
                ]
              }
            }),
          ]
        }
      })
    }
  },
])


// 监听区域
watch(() => props.tabledata, () => {
  calculation()
})
// 生命周期区域
onMounted(() => {
  calculation()
  window.addEventListener('resize', () => {
    calculation()
  })
})
onUnmounted(() => {
  window.removeEventListener('resize', () => {
    calculation()
  })
})


// 初始化区域
getcollumns()
</script>

<style scoped>
</style>
